<?php


namespace app\api\services;

use app\common\libs\Singleton;
use app\common\models\Schools\Schools;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class SchoolsService
{
    use Singleton;


    /**
     * @param $searchKey
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function schoolsList($page, $pageSize ,$searchKey): array
    {
        $where = [
            ['status', '=', 1],
            ['deleted' ,'=' ,0]
        ];
        if( !empty( $searchKey ) ) $where[] = ['title', 'like', "%{$searchKey}%"];
        $schoolsList = Schools::getInstance()
            ->where($where)
            ->limit(($page - 1) * $pageSize, $pageSize)
            ->field('id,create_at,update_at,type,title,content,cover_image,media_url,study_numbers,is_free,status')
            ->order('sort desc,id desc')
            ->select();
        if (empty($schoolsList)) {
            return [];
        }
        $list = $schoolsList->toArray();
        return $list;
    }
    public function getInfo( $id ): array
    {
        $where = [
            ['id', '=', $id]
        ];
        $field = 'id,create_at,update_at,type,title,content,cover_image,media_url,study_numbers,is_free,status';
        $schools = Schools::getInstance()->where($where)->field($field)->find();
        return empty($schools) ? [] : $schools->toArray();
    }
    public function updateNumber( $id )
    {
        $where = [
            ['id', '=', $id]
        ];
        $schools = Schools::getInstance()->where($where)->inc('study_numbers' ,'1')->update();
        return true;
    }

}